using System;
using System.ComponentModel;
using Microsoft.PowerShell.Host.ISE;

namespace Empanada
{
    public class PowerShellTabSelectedFileMonitor
    {
        public event ISEFileEventHandler SelectedFileChanged;
        
        private readonly PowerShellTab _tab;

        public PowerShellTabSelectedFileMonitor(PowerShellTab tab)
        {
            _tab = tab;
            _tab.PropertyChanged += TabPropertyChanged;
            ((INotifyPropertyChanged)_tab.Files).PropertyChanged += FilesPropertyChanged;
        }

        public ISEFile SelectedFile
        {
            get
            {
                return _tab.ExpandedScript ? _tab.Files.SelectedFile : null;
            }
            set {
                if (value == SelectedFile) return;
                _tab.Files.SetSelectedFile(value);
                _tab.ExpandedScript = true;
                OnSelectedFileChanged(value);
            }
        }

        private void FilesPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (!_tab.ExpandedScript) return;

            var files = (ISEFileCollection)sender;
            if (e.PropertyName.Equals("SelectedFile", StringComparison.InvariantCultureIgnoreCase))
            {
                OnSelectedFileChanged(files.SelectedFile);
            }
        }

        private void TabPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (!e.PropertyName.Equals("ExpandedScript", StringComparison.InvariantCultureIgnoreCase)) return;

            var tab = (PowerShellTab)sender;
            ISEFile selectedFile = null;
            if (tab.ExpandedScript)
            {
                selectedFile = tab.Files.SelectedFile;
            }
            OnSelectedFileChanged(selectedFile);
        }

        protected void OnSelectedFileChanged(ISEFile file)
        {
            var handler = SelectedFileChanged;
            if (handler != null) handler(this, new ISEFileEventArgs {File = file});
        }
    
    }
}